package org.jbelis.yodaquotes.store.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.Persistent;

import org.jbelis.yodaquotes.Quote;
import org.jbelis.yodaquotes.store.QuoteStore;

public class JDOQuoteStore implements QuoteStore {

	public List<Quote> findByAuthor(String author) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		String query = "select from " + Quote.class.getName();
		if (author != null) {
			query += "where author == " + author;
		}
		return (List<Quote>) pm.newQuery(query).execute();
	}

	public List<Quote> findByText(String text) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		String query = "select from " + Quote.class.getName();
		if (text != null) {
			query += "where text == " + text;
		}
		return (List<Quote>) pm.newQuery(query).execute();
	}

	public Quote store(Quote quote) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(quote);
		} finally {
			pm.close();
		}
		return quote;
	}

}
